package com.banciyuan.bcywebview.biz.main.mineinfo.reward;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GiftApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.fragment.BaseFragment;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.PayStatus;

/**
 * Created by hy on 2016/5/16.
 */
public class MyRewardActivity extends BaseActivity {

    public final static int GO_OPEN_REWARD = 1233;

    private List<BaseFragment> mList = new ArrayList<>();
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private FragmentManager fm;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private SendFeedFragment sendedFragment;
    private ReceiveFeedFragment receivedFragment;
    private OpenRewardFragment openRewardFragment;
    private TextView function_tv;
    private RequestQueue mQueue;
    private PayStatus payStatus;
    private int type;
    private MyAdapter myAdapter;
    private String[] tabs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myreward_layout);
        initArgs();
        initProgressbar();
        initActionbar();
        initUi();
        initData();
        initAction();
    }

    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + GiftApi.getPayStatus();
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, MyRewardActivity.this)) {
                    try {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        payStatus = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), PayStatus.class);
                        if (!MyRewardActivity.this.isFinishing()) {
                            renderUi();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, MyRewardActivity.this, params);
        StringRequest stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, onErrorProxy);
        mQueue.add(stringRequest);
    }

    private void renderUi() {
        mProgressbarHelper.onSuccess();
        getFragment();
        myAdapter = new MyAdapter(fm);
        mViewPager.setAdapter(myAdapter);
        mTabLayout.setTabsFromPagerAdapter(myAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setCurrentItem(type);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initArgs() {
        type = getIntent().getIntExtra(gotoUtil.INTENT_VALUE_ONE, 0);
        mQueue = VolleyQueue.getRquest(this);
        tabs = new String[]{getString(R.string.sended_reward), getString(R.string.received_reward)};
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.my_reward));
        mActionbarHelper.addItemOneText(getString(R.string.feed_setting));
        function_tv = (TextView) mActionBarView.findViewById(R.id.base_action_bar_home_text_item);
        function_tv.setTextSize(12);
        function_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(MyRewardActivity.this, RewardSettingActivity.class, payStatus);
            }
        });
    }

    @Override
    protected void initUi() {
        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        mViewPager = (ViewPager) findViewById(R.id.pager);
    }


    private void getFragment() {
        fm = getSupportFragmentManager();
        initSendFragment();
        initReceivedFragment();
        initOpenFragment();
        mList.clear();
        if (payStatus.isStatus()) {
            mList.add(sendedFragment);
            mList.add(receivedFragment);
            tabs[1] = getString(R.string.received_reward);
            function_tv.setVisibility(View.VISIBLE);
        } else {
            mList.add(sendedFragment);
            mList.add(openRewardFragment);
            tabs[1] = getString(R.string.feed_open);
            function_tv.setVisibility(View.GONE);
        }
    }

    private void initReceivedFragment() {
        receivedFragment = new ReceiveFeedFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("pay_status", payStatus);
        if (type == 1) {
            bundle.putSerializable("pre_load", true);
        } else {
            bundle.putSerializable("pre_load", false);
        }
        receivedFragment.setArguments(bundle);
    }

    private void initSendFragment() {
        sendedFragment = new SendFeedFragment();
        Bundle bundle = new Bundle();
        if (type == 0) {
            bundle.putSerializable("pre_load", true);
        } else {
            bundle.putSerializable("pre_load", false);
        }
        sendedFragment.setArguments(bundle);
    }

    private void initOpenFragment() {
        openRewardFragment = new OpenRewardFragment();
    }

    class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabs[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
